/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.sais.eswn.net;

import java.awt.Color;
import org.sais.eswn.core.GameCore;
import org.sais.eswn.tool.Tools;

/**
 *
 * @author Romulus
 */
public class ClientMessageDispatcher extends CommonMessageDispatcher {

    public ClientMessageDispatcher(ClientSock parentSock) {
        super(parentSock);
    }

    @Override
    public void dispatch(String instr) {
        if (clientMessageDispatch(instr)) {
            return;
        }
        if (watcherMessageDispatch(instr)) {
            return;
        }
        commonMessageDispath(instr, true);
    }

    /**
     *
     * @param instr
     * @return true if the message is dispatched.
     */
    private boolean clientMessageDispatch(String ins) {
        String cmd;
        cmd = "$YOUAREAPPLICANT:";
        if (ins.startsWith(cmd)) {
            ((ClientSock) mParentSock).newGame();
            return true;
        }
        cmd = "$NOGAMEYET:";
        if (ins.startsWith(cmd)) {
            mParentSock.setMessage("No game running yet.");
            return true;
        }
        cmd = "$YOUAREWATCHER:";
        if (ins.startsWith(cmd)) {
            if (((ClientSock) mParentSock).isWatcher()) {
                ((ClientSock) mParentSock).newGame();
                send("$GIVEMECURRENT:");
            } else {
                mParentSock.setMessage("The game has started.");
                mParentSock.closeSocket();
            }
            return true;
        }
        cmd = "$VERSION:";
        if (ins.startsWith(cmd)) {
            if (!GameCore.sVersion.equals(ins.substring(cmd.length()))) {
                core().insertMessage(Tools.parseLocale(21,
                        new String[]{GameCore.sVersion, ins.substring(cmd.length())}), Color.RED);
                send("$DIFFERENTVERSION:" + GameCore.sVersion);
            }
            return true;
        }
        if (ins.startsWith(cmd)) {
            return true;
        }
        return false;
    }

    private boolean watcherMessageDispatch(String ins) {
        if (!ins.startsWith("$WATCH")) {
            return false;
        }
        String cmd;
        cmd = "$WATCHHOST:";
        if (ins.startsWith(cmd)) {
            ins = mParentSock.Fix(ins.substring(cmd.length()));
            commonMessageDispath(ins, false);
            return true;
        }
        cmd = "$WATCHCLIENT:";
        if (ins.startsWith(cmd)) {
            ins = mParentSock.Fix(ins.substring(cmd.length()));
            commonMessageDispath(ins, true);
            return true;
        }
        return false;
    }

}
